package com.hornsun.jwt;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author 编译中、、
 * @date 2017/12/24
 */
public class JwtAuthenticationProvider implements AuthenticationProvider {
    @Resource
    private JwtProperties jwtProperties;

    private final Logger logger = LoggerFactory.getLogger(JwtAuthenticationProvider.class);

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        RawAccessJwtToken rawAccessToken = (RawAccessJwtToken) authentication.getCredentials();

        Jws<Claims> jwsClaims = rawAccessToken.parseClaims(jwtProperties.getSigningKey());
        Claims claims = jwsClaims.getBody();

        // username
        String subject = claims.getSubject();
        String id = claims.get("id", String.class);
        List<?> authorities = claims.get("authorities", List.class);
        String password = (String) claims.get("password");
        AuthorizedClient user = new AuthorizedClient(id, subject, password, authorities);
        logger.debug("Extract user info from JWT anonymous, id: {}, username: {}", id, subject);
        return new JwtAuthenticationToken(user, user.getAuthorities());
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return (JwtAuthenticationToken.class.isAssignableFrom(authentication));
    }
}
